// soil-data.controller.ts
import { Inject, Controller, Post, Get, Put, Del, Body, Query, Param, Files } from '@midwayjs/core';
import { ApiTags, ApiOperation } from '@midwayjs/swagger';
import { SoilDataService } from '../service/soilData.service';
import { 
  CreateSoilDataDTO, 
  UpdateSoilDataDTO, 
  QuerySoilDataDTO, 
  DeleteSoilDataDTO,
  ImportSoilDataDTO 
} from '../dto/soilDataDto';

@ApiTags(['土壤数据管理'])
@Controller('/api/soil-data')
export class SoilDataController {
  @Inject()
  soilDataService: SoilDataService;

  @ApiOperation({ summary: '创建土壤数据' })
  @Post('/')
  async create(@Body() data: CreateSoilDataDTO) {
    const result = await this.soilDataService.create(data);
    return { success: true, data: result };
  }

  @ApiOperation({ summary: '更新土壤数据' })
  @Put('/')
  async update(@Body() data: UpdateSoilDataDTO) {
    const result = await this.soilDataService.update(data);
    return { success: true, data: result };
  }

  @ApiOperation({ summary: '删除土壤数据' })
  @Del('/:id')
  async delete(@Param('id') id: number) {
    const result = await this.soilDataService.delete(id);
    return { success: result };
  }

  @ApiOperation({ summary: '根据ID查询土壤数据' })
  @Get('/:id')
  async findById(@Param('id') id: number) {
    const result = await this.soilDataService.findById(id);
    return { success: true, data: result };
  }

  @ApiOperation({ summary: '分页查询土壤数据' })
  @Get('/page')
  async findByPage(@Query() query: QuerySoilDataDTO) {
    const result = await this.soilDataService.findByPage(query);
    return { success: true, data: result };
  }

  @ApiOperation({ summary: '上传Excel导入土壤数据' })
  @Post('/import')
  async importFromExcel(@Files() files) {
    if (!files || files.length === 0) {
      return { success: false, message: '请上传文件' };
    }
    
    const file = files[0];
    if (!file.mimetype.includes('excel') && !file.mimetype.includes('spreadsheetml')) {
      return { success: false, message: '请上传Excel文件' };
    }
    
    try {
      const result = await this.soilDataService.importFromExcel(file.data);
      return { 
        success: true, 
        data: result,
        message: `共${result.total}条数据，成功导入${result.success}条，失败${result.fail}条`
      };
    } catch (error) {
      return {
        success: false,
        message: `导入失败: ${error.message}`
      };
    }
  }

  @ApiOperation({ summary: '批量创建土壤数据' })
  @Post('/batch')
  async batchCreate(@Body() data: ImportSoilDataDTO) {
    const result = await this.soilDataService.batchCreate(data);
    return { success: true, data: result };
  }
}
